﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Remote_Desktop_Administrator
{
    public partial class MainForm : Form
    {
        // place-holder for last node in treeview selected
        private TreeNode m_OldSelectNode;
        // place-holder for top axmstsclib control
        //AxMSTSCLib.AxMsRdpClient6NotSafeForScripting AxTop = new AxMSTSCLib.AxMsRdpClient6NotSafeForScripting();
   
        //
        // Overview:
        // Default constructor
        //
        public MainForm()
        {
            InitializeComponent();
        }

        //
        // Overview:
        // Closes form & program
        //
        private void mnuFileExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //
        // Overview:
        // Shows about box
        //
        private void mnuHelpAbout_Click(object sender, EventArgs e)
        {
            AboutForm frmAbout = new AboutForm();
            frmAbout.ShowDialog();
        }

        //
        // Overview:
        // Calls method to connect to selected server
        //
        private void toolStripMenuItemConnect_Click(object sender, EventArgs e)
        {
            int intServerIndex = -1;
            intServerIndex = Connection.FindServer(treeViewMain.SelectedNode.Name.ToString());
            bool blnConsole = false;
            bool blnCreds = true;

            AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1 = Connection.FindRdpControl(this, treeViewMain.SelectedNode.Name.ToString());

            if (intServerIndex != -1)
            {
                if (Ax1 != null)
                {
                    Connection.DisconnectSession(Ax1, this);
                }

                AxMSTSCLib.AxMsRdpClient6NotSafeForScripting newRdpControl = new AxMSTSCLib.AxMsRdpClient6NotSafeForScripting();
                Controls.Add(newRdpControl);
                Connection.ConnectSession(newRdpControl, splitContainerMain, intServerIndex, blnConsole, blnCreds);
                //AxTop = newRdpControl;
                toolStripStatusLabel.Text = "Server -> " + treeViewMain.SelectedNode.Text.ToString();
                
                //for color highlight
                treeViewMain.SelectedNode.BackColor = Color.DarkGray;
                Connection.arrConnections[intServerIndex, 13] = "true";
            }
        }

        //
        // Overview:
        // Calls method to connect to selected server, but to console session
        //
        private void toolStripMenuItemConnectToConsole_Click(object sender, EventArgs e)
        {
            int intServerIndex = -1;
            intServerIndex = Connection.FindServer(treeViewMain.SelectedNode.Name.ToString());
            bool blnConsole = true;
            bool blnCreds = true;

            AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1 = Connection.FindRdpControl(this, treeViewMain.SelectedNode.Name.ToString());

            if (intServerIndex != -1)
            {
                if (Ax1 != null)
                {
                    Connection.DisconnectSession(Ax1, this);
                }

                AxMSTSCLib.AxMsRdpClient6NotSafeForScripting newRdpControl = new AxMSTSCLib.AxMsRdpClient6NotSafeForScripting();
                Controls.Add(newRdpControl);
                Connection.ConnectSession(newRdpControl, splitContainerMain, intServerIndex, blnConsole, blnCreds);
                //AxTop = newRdpControl;
                
                toolStripStatusLabel.Text = "Server -> " + treeViewMain.SelectedNode.Text.ToString();
                
                //for color highlight
                treeViewMain.SelectedNode.BackColor = Color.DarkGray;
                Connection.arrConnections[intServerIndex, 13] = "true";
            }
        }

        //
        // Overview:
        // Disconnects selected session
        //
        private void toolStripMenuItemDisconnect_Click(object sender, EventArgs e)
        {
            int intServerIndex = -1;
            intServerIndex = Connection.FindServer(treeViewMain.SelectedNode.Name.ToString());
            
            AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1 = Connection.FindRdpControl(this, treeViewMain.SelectedNode.Name.ToString());
            Connection.DisconnectSession(Ax1, this);

            toolStripStatusLabel.Text = "Server -> " + treeViewMain.SelectedNode.Text.ToString();

            if (intServerIndex != -1)
            {
                // color highlights
                Connection.arrConnections[intServerIndex, 13] = "false";
                treeViewMain.SelectedNode.BackColor = Color.White;
            }

            int x = splitContainerMain.Panel2.Controls.GetChildIndex(axMsRdpMain);
            if (x > 0)
            {
                axMsRdpMain.BringToFront();
            }
        }

        //
        // Overview:
        // Calls method to update selected connection
        //
        private void editConnectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Connection.UpdateConnection(treeViewMain.SelectedNode.Name.ToString(), treeViewMain);
        }

        //
        // Overview:
        // Deletes selected treeview node and associated axmstsclib object
        //
        private void deleteConnectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeViewMain.SelectedNode != null)
            {
                DialogResult diagResult = MessageBox.Show("Are you sure you want to delete connection named: " + treeViewMain.SelectedNode.Text.ToString() + "?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (diagResult == DialogResult.Yes)
                {
                    AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1 = Connection.FindRdpControl(this, treeViewMain.SelectedNode.Name.ToString());
                    Connection.DisconnectSession(Ax1, this);
                    Connection.DeleteConnection(treeViewMain.SelectedNode.Name.ToString(), treeViewMain);
                    toolStripStatusLabel.Text = "";

                    int x = splitContainerMain.Panel2.Controls.GetChildIndex(axMsRdpMain);
                    if (x > 0)
                    {
                        axMsRdpMain.BringToFront();
                    }
                }
            }
        }

        //
        // Overview:
        // Brings selected node to top/foreground for use if it is not already at the top
        //
        private void treeViewMain_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1 = Connection.FindRdpControl(this, e.Node.Name.ToString());

                if (e.Node.Text != "(Default)" && e.Node.Tag.ToString() != "Folder")
                    toolStripStatusLabel.Text = "Server -> " + e.Node.Text;
                else
                    toolStripStatusLabel.Text = "Folder -> " + e.Node.Text;

                if (Ax1 != null)
                {
                    int x = splitContainerMain.Panel2.Controls.GetChildIndex(Ax1);

                    Ax1.BringToFront();
                    SendKeys.Send("{TAB}");
                    SendKeys.Send("{TAB}");
                    SendKeys.Send("{TAB}");
                }
                else
                {
                    axMsRdpMain.BringToFront();
                    if (e.Node.Text != "(Default)" && e.Node.Tag.ToString() != "Folder")
                        axMsRdpMain.DisconnectedText = "Disconnected from " + e.Node.Text + " ... ";
                    else
                        axMsRdpMain.DisconnectedText = "";
                }
            }
        }

        //
        // Overview:
        // Calls save dialog box
        //
        private void mnuFileSave_Click(object sender, EventArgs e)
        {
            saveFileDialog.ShowDialog();
        }

        //
        // Overview:
        // Calls method to dump arrays to text file
        //
        private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            string Fn1 = saveFileDialog.FileName;
            bool blnSuccess = Connection.SaveSettings(Fn1);

            if (blnSuccess)
            {
                //MessageBox.Show("File saved.");
            }
            else
            {
                MessageBox.Show("File not saved successfully.");
            }
        }

        //
        // Overview:
        // Calls method to launch new connection form
        //
        private void mnuFileNewConnection_Click_1(object sender, EventArgs e)
        {
            ConnectionForm frmNewConnection = new ConnectionForm();
            // pass reference to treeview object to new form so it can be refreshed right after connection is added!
            frmNewConnection.ReceiveTreeViewRef(treeViewMain);
            frmNewConnection.Text = "Add New Connection";
            frmNewConnection.prop_UpdateConnection = false;
            frmNewConnection.ShowDialog();
        }

        //
        // Overview:
        // Controls how context menu is shown
        // Code snippet adapted from: http://support.microsoft.com/kb/810001
        //
        private void treeViewMain_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                // Point where the mouse is clicked.
                Point p = new Point(e.X, e.Y);

                // Get the node that the user has clicked.
                TreeNode node = treeViewMain.GetNodeAt(p);
                if (node != null)
                {
                    // Select the node the user has clicked.
                    // The node appears selected until the menu is displayed on the screen.
                    m_OldSelectNode = treeViewMain.SelectedNode;
                    treeViewMain.SelectedNode = node;

                    // Find the appropriate ContextMenu depending on the selected node.
                    if (Convert.ToString(node.Tag) == "Connection")
                        contextMenuStripMain.Show(treeViewMain, p);
                    if (Convert.ToString(node.Tag) == "Folder")
                        contextMenuStripFold.Show(treeViewMain, p);

                    // Highlight the selected node.
                    treeViewMain.SelectedNode = m_OldSelectNode;
                    m_OldSelectNode = null;
                }
                else
                {
                    SendKeys.Send("{TAB}");
                    SendKeys.Send("{TAB}");
                    SendKeys.Send("{TAB}");
                }
            }

            // trick to send focus back to topmost rdp control - using the regular focus method did not work...
            if (e.Button == MouseButtons.Left)
            {
                // Point where the mouse is clicked.
                Point p = new Point(e.X, e.Y);

                // Get the node that the user has clicked.
                TreeNode node = treeViewMain.GetNodeAt(p);
                if (node != null)
                {
                    // nothing yet...
                }
                else
                {
                    SendKeys.Send("{TAB}");
                    SendKeys.Send("{TAB}");
                    SendKeys.Send("{TAB}");
                }
            }
        }
        
        //
        // Overview:
        // Calls method to delete the selected folder
        //
        private void deleteFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult diagResult = MessageBox.Show("Are you sure you want to delete folder named: " + treeViewMain.SelectedNode.Text.ToString() + "?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (diagResult == DialogResult.Yes)
                Connection.DeleteFolder(treeViewMain.SelectedNode.Name.ToString(), treeViewMain);
        }

        //
        // Overview:
        // Launches new folder form with rename parameters
        //
        private void renameFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderForm frm1 = new FolderForm();
            frm1.ReceiveTreeView(treeViewMain);
            frm1.prop_UpdateFolder = true;
            frm1.ShowDialog();
        }

        //
        // Overview:
        // Launches open file dialog box
        //
        private void openSettingsFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Connection.intRowConn == 0 && Connection.intRowFold == 0)
            {
                Connection.arrConnections.Initialize();
                Connection.arrFolders.Initialize();
                toolStripStatusLabel.Text = "";
                int x = splitContainerMain.Panel2.Controls.GetChildIndex(axMsRdpMain);
                if (x > 0)
                {
                    axMsRdpMain.BringToFront();
                }
                treeViewMain.Nodes.Clear();
                openFileDialog.ShowDialog();
            }
            else
            {
                DialogResult diagResult = MessageBox.Show("Loading a file will clear current settings...Are you sure you want to load a file?", "Confirm Load", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (diagResult == DialogResult.Yes)
                {
                    Connection.arrConnections.Initialize();
                    Connection.arrFolders.Initialize();
                    Connection.intRowConn = 0;
                    Connection.intRowFold = 0;
                    toolStripStatusLabel.Text = "";
                    int x = splitContainerMain.Panel2.Controls.GetChildIndex(axMsRdpMain);
                    if (x > 0)
                    {
                        axMsRdpMain.BringToFront();
                    }
                    treeViewMain.Nodes.Clear();
                    openFileDialog.ShowDialog();
                }
            }
        }
       
        //
        // Overview:
        // Takes selected file for open and processes it
        //
        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            string strFn = openFileDialog.FileName;
            bool blnSuccess = Connection.LoadSettings(strFn);
            if (blnSuccess)
            {
                //MessageBox.Show("File loaded.");
                Connection.RefreshTreeView(treeViewMain);
            }
            else
                MessageBox.Show("File not loaded successfully.");
        }
        
        //
        // Overview:
        // Confirm on main form exit
        //
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Connection.intRowConn > 0 || Connection.intRowFold > 0)
            {
                DialogResult diagResult = MessageBox.Show("Do you really want to exit? Unsaved settings will be lost.", "Confirm Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (diagResult == DialogResult.No)
                    e.Cancel = true;
            }
        }

        //
        // Overview:
        // Trick to keep the selected tree node from assuming the default (index 0) image...don't
        // know why it does this, but this snippet works!
        //
        private void treeViewMain_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            e.Node.SelectedImageIndex = e.Node.ImageIndex;
        }

        //
        // Overview:
        // Trick to pass "focus" back to the top axmstsclib control if splitter is changed to resize panes 
        //
        private void splitContainerMain_SplitterMoved(object sender, SplitterEventArgs e)
        {
            SendKeys.Send("{TAB}");
            SendKeys.Send("{TAB}");
        }

        private void connectWoCredentialsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int intServerIndex = -1;
            intServerIndex = Connection.FindServer(treeViewMain.SelectedNode.Name.ToString());
            bool blnConsole = true;
            bool blnCreds = false;

            AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1 = Connection.FindRdpControl(this, treeViewMain.SelectedNode.Name.ToString());

            if (intServerIndex != -1)
            {
                if (Ax1 != null)
                {
                    Connection.DisconnectSession(Ax1, this);
                }

                AxMSTSCLib.AxMsRdpClient6NotSafeForScripting newRdpControl = new AxMSTSCLib.AxMsRdpClient6NotSafeForScripting();
                Controls.Add(newRdpControl);
                Connection.ConnectSession(newRdpControl, splitContainerMain, intServerIndex, blnConsole, blnCreds);
                //AxTop = newRdpControl;

                toolStripStatusLabel.Text = "Server -> " + treeViewMain.SelectedNode.Text.ToString();

                //for color highlight
                treeViewMain.SelectedNode.BackColor = Color.DarkGray;
                Connection.arrConnections[intServerIndex, 13] = "true";
            }
        }

        private void donateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("If you like what you see and feel this tool is useful, please donate!", "Donation via PayPal", MessageBoxButtons.OK, MessageBoxIcon.Information);
            System.Diagnostics.Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=jchoponis%40gmail%2ecom&lc=US&item_name=Justin%20Choponis&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted");
        }
    }
}